package hamsterpolice.todo.model;

import hamsterpolice.todo.R;
import hamsterpolice.todo.data.ToDoListTable;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ToDoItemCursorAdapter extends SimpleCursorAdapter {

	private int layout;
	private static final String[] cols = new String[] {
			ToDoListTable.COLUMN_NAME, ToDoListTable.COLUMN_COMPLETED,
			ToDoListTable.COLUMN_DUE_DATE };

	private static final int[] views = new int[] { R.id.name,
			R.id.strikeThrough, R.id.dueDate };

	public ToDoItemCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, int flags) {

		super(context, layout, c, cols, views, flags);
		this.layout = layout;

	}

	@Override
	public View newView(Context context, Cursor c, ViewGroup parent) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(layout, parent, false);

		TextView name = (TextView) view.findViewById(R.id.name);
		name.setText(c.getString(c.getColumnIndex(ToDoListTable.COLUMN_NAME)));

		view.findViewById(R.id.strikeThrough)
				.setVisibility(
					c.getInt(c.getColumnIndex(ToDoListTable.COLUMN_COMPLETED)) == 0 
						? View.GONE
						: View.VISIBLE);

		if (!c.isNull(c.getColumnIndex(ToDoListTable.COLUMN_DUE_DATE))) {
			TextView dueDate = (TextView) view.findViewById(R.id.dueDate);
			Date due = new Date();
			DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.SHORT);
			due.setTime(c.getLong(c
					.getColumnIndex(ToDoListTable.COLUMN_DUE_DATE)));
			dueDate.setText(dateFormat.format(due));
		}

		return view;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		String name = cursor.getString(cursor
				.getColumnIndex(ToDoListTable.COLUMN_NAME));
		TextView nameText = (TextView) view.findViewById(R.id.name);

		if (nameText != null)
			nameText.setText(name);
	}

}
